package com.rcl.httpurlconnection.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.rcl.httpurlconnection.R;
import com.rcl.httpurlconnection.adapter.ItemListAdapter;
import com.rcl.httpurlconnection.bean.ItemBean;
import com.rcl.httpurlconnection.interfaces.IitemCallBackView;
import com.rcl.httpurlconnection.presenter.ItemPresenter;

import java.util.List;

/*
 * class title:
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2020/10/22.
 * PS: Not easy to write code, please indicate.
 */
public class ItemListActivity extends AppCompatActivity implements IitemCallBackView {

    private RecyclerView mRecyclerList;
    private ItemPresenter mInstance;
    private static Handler mHandler;
    public static final int WHAT_LOADER_RESULT = 1;
    private ItemListAdapter mItemListAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_list);

        initView();
    }

    private void initView() {
        mRecyclerList = findViewById(R.id.rv_list);
        mRecyclerList.setLayoutManager(new LinearLayoutManager(this));
        mItemListAdapter = new ItemListAdapter();
        mRecyclerList.setAdapter(mItemListAdapter);


        mHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case WHAT_LOADER_RESULT:
                        List<ItemBean.DataBean> list = (List<ItemBean.DataBean>) msg.obj;
                        mItemListAdapter.setData(list);
                        break;
                }
            }
        };

        initPresenter();
    }

    private void initPresenter() {
        mInstance = ItemPresenter.getInstance();
        mInstance.registerCallBackView(this);

        new Thread(new Runnable() {
            @Override
            public void run() {
                mInstance.getItemData();
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mInstance != null) {
            mInstance.unregisterCallBackView(this);
        }
    }

    @Override
    public void onItemData(List<ItemBean.DataBean> list) {
        Message message = mHandler.obtainMessage();
        message.what = WHAT_LOADER_RESULT;
        message.obj = list;
        mHandler.sendMessage(message);
    }
}
